// 交易终端 Mock 数据
export interface OrderBookItem {
  price: number
  size: number
  total: number
}

export interface OrderBook {
  bids: OrderBookItem[]  // 买单
  asks: OrderBookItem[]  // 卖单
  lastPrice: number
  priceChange: number
  priceChangePercent: number
}

export interface Trade {
  id: number
  price: number
  size: number
  time: string
  side: 'buy' | 'sell'
}

export interface TradingPair {
  symbol: string
  baseAsset: string
  quoteAsset: string
  price: number
  change24h: number
  volume24h: number
  high24h: number
  low24h: number
  icon: string
}

export interface CreateOrderRequest {
  symbol: string
  side: 'buy' | 'sell'
  type: 'market' | 'limit' | 'stop'
  quantity: number
  price?: number
  stopPrice?: number
  timeInForce?: 'GTC' | 'IOC' | 'FOK'
}

export interface Order {
  id: string
  symbol: string
  side: 'buy' | 'sell'
  type: 'market' | 'limit' | 'stop'
  quantity: number
  price?: number
  filled: number
  status: 'pending' | 'filled' | 'canceled' | 'rejected'
  createTime: string
  updateTime: string
}

export interface OrderHistory extends Order {
  executedPrice?: number
  fee: number
  feeAsset: string
  pnl?: number
  commission: number
  commissionAsset: string
  fills: OrderFill[]
}

export interface OrderFill {
  id: string
  price: number
  quantity: number
  commission: number
  commissionAsset: string
  time: string
}

export interface OrderQueryParams {
  symbol?: string
  status?: 'pending' | 'filled' | 'canceled' | 'rejected' | 'all'
  side?: 'buy' | 'sell' | 'all'
  type?: 'market' | 'limit' | 'stop' | 'all'
  startTime?: string
  endTime?: string
  page?: number
  pageSize?: number
}

export interface Balance {
  asset: string
  free: number
  locked: number
  total: number
}

// Mock 交易对数据
export const mockTradingPairs: TradingPair[] = [
  {
    symbol: 'BTCUSDT',
    baseAsset: 'BTC',
    quoteAsset: 'USDT',
    price: 44180.50,
    change24h: 2.35,
    volume24h: 28459.32,
    high24h: 44850.00,
    low24h: 43120.00,
    icon: '₿'
  },
  {
    symbol: 'ETHUSDT',
    baseAsset: 'ETH',
    quoteAsset: 'USDT',
    price: 2642.85,
    change24h: 1.89,
    volume24h: 156842.55,
    high24h: 2698.45,
    low24h: 2580.30,
    icon: 'Ξ'
  },
  {
    symbol: 'SOLUSDT',
    baseAsset: 'SOL',
    quoteAsset: 'USDT',
    price: 96.22,
    change24h: -1.45,
    volume24h: 89456.78,
    high24h: 98.45,
    low24h: 94.85,
    icon: '◎'
  },
  {
    symbol: 'ADAUSDT',
    baseAsset: 'ADA',
    quoteAsset: 'USDT',
    price: 0.4698,
    change24h: -2.63,
    volume24h: 425896.32,
    high24h: 0.4825,
    low24h: 0.4580,
    icon: '₳'
  }
]

// Mock 订单簿数据
export const mockOrderBook: OrderBook = {
  bids: [
    { price: 44175.50, size: 0.25, total: 0.25 },
    { price: 44170.00, size: 0.48, total: 0.73 },
    { price: 44165.25, size: 1.25, total: 1.98 },
    { price: 44160.00, size: 0.85, total: 2.83 },
    { price: 44155.50, size: 2.15, total: 4.98 },
    { price: 44150.00, size: 1.65, total: 6.63 },
    { price: 44145.25, size: 0.95, total: 7.58 },
    { price: 44140.00, size: 3.25, total: 10.83 },
    { price: 44135.50, size: 1.85, total: 12.68 },
    { price: 44130.00, size: 2.45, total: 15.13 }
  ],
  asks: [
    { price: 44180.50, size: 0.35, total: 0.35 },
    { price: 44185.00, size: 0.68, total: 1.03 },
    { price: 44190.25, size: 1.45, total: 2.48 },
    { price: 44195.00, size: 0.95, total: 3.43 },
    { price: 44200.50, size: 2.25, total: 5.68 },
    { price: 44205.00, size: 1.75, total: 7.43 },
    { price: 44210.25, size: 1.15, total: 8.58 },
    { price: 44215.00, size: 3.45, total: 12.03 },
    { price: 44220.50, size: 1.95, total: 13.98 },
    { price: 44225.00, size: 2.65, total: 16.63 }
  ],
  lastPrice: 44180.50,
  priceChange: 1035.25,
  priceChangePercent: 2.35
}

// Mock 最近成交数据
export const mockRecentTrades: Trade[] = [
  { id: 1, price: 44180.50, size: 0.25, time: '14:32:45', side: 'buy' },
  { id: 2, price: 44175.00, size: 0.48, time: '14:32:42', side: 'sell' },
  { id: 3, price: 44182.25, size: 1.25, time: '14:32:38', side: 'buy' },
  { id: 4, price: 44178.50, size: 0.85, time: '14:32:35', side: 'sell' },
  { id: 5, price: 44185.00, size: 2.15, time: '14:32:30', side: 'buy' },
  { id: 6, price: 44180.25, size: 1.65, time: '14:32:28', side: 'buy' },
  { id: 7, price: 44176.00, size: 0.95, time: '14:32:25', side: 'sell' },
  { id: 8, price: 44183.50, size: 3.25, time: '14:32:20', side: 'buy' },
  { id: 9, price: 44179.25, size: 1.85, time: '14:32:18', side: 'sell' },
  { id: 10, price: 44181.00, size: 2.45, time: '14:32:15', side: 'buy' }
]

// Mock 余额数据
export const mockBalances: Balance[] = [
  { asset: 'USDT', free: 25680.50, locked: 5420.25, total: 31100.75 },
  { asset: 'BTC', free: 0.58642, locked: 0.12500, total: 0.71142 },
  { asset: 'ETH', free: 12.8456, locked: 2.1500, total: 14.9956 },
  { asset: 'SOL', free: 85.2500, locked: 15.0000, total: 100.2500 },
  { asset: 'ADA', free: 2580.50, locked: 420.00, total: 3000.50 }
]

// Mock 当前订单
export const mockActiveOrders: Order[] = [
  {
    id: 'ORD001',
    symbol: 'BTCUSDT',
    side: 'buy',
    type: 'limit',
    quantity: 0.5,
    price: 43500.00,
    filled: 0,
    status: 'pending',
    createTime: '2024-02-20 14:25:30',
    updateTime: '2024-02-20 14:25:30'
  },
  {
    id: 'ORD002',
    symbol: 'ETHUSDT',
    side: 'sell',
    type: 'limit',
    quantity: 2.0,
    price: 2700.00,
    filled: 0,
    status: 'pending',
    createTime: '2024-02-20 14:20:15',
    updateTime: '2024-02-20 14:20:15'
  }
]

// Mock 订单历史数据
export const mockOrderHistory: OrderHistory[] = [
  {
    id: 'ORD100',
    symbol: 'BTCUSDT',
    side: 'buy',
    type: 'market',
    quantity: 0.25,
    filled: 0.25,
    status: 'filled',
    executedPrice: 44180.50,
    fee: 11.05,
    feeAsset: 'USDT',
    pnl: 125.50,
    commission: 11.05,
    commissionAsset: 'USDT',
    createTime: '2024-02-20 13:45:20',
    updateTime: '2024-02-20 13:45:22',
    fills: [
      {
        id: 'FILL001',
        price: 44180.50,
        quantity: 0.25,
        commission: 11.05,
        commissionAsset: 'USDT',
        time: '2024-02-20 13:45:22'
      }
    ]
  },
  {
    id: 'ORD101',
    symbol: 'ETHUSDT',
    side: 'sell',
    type: 'limit',
    quantity: 1.5,
    price: 2650.00,
    filled: 1.5,
    status: 'filled',
    executedPrice: 2650.00,
    fee: 3.98,
    feeAsset: 'USDT',
    pnl: -45.30,
    commission: 3.98,
    commissionAsset: 'USDT',
    createTime: '2024-02-20 12:30:15',
    updateTime: '2024-02-20 12:35:42',
    fills: [
      {
        id: 'FILL002',
        price: 2650.00,
        quantity: 1.0,
        commission: 2.65,
        commissionAsset: 'USDT',
        time: '2024-02-20 12:35:40'
      },
      {
        id: 'FILL003',
        price: 2650.00,
        quantity: 0.5,
        commission: 1.33,
        commissionAsset: 'USDT',
        time: '2024-02-20 12:35:42'
      }
    ]
  },
  {
    id: 'ORD102',
    symbol: 'SOLUSDT',
    side: 'buy',
    type: 'limit',
    quantity: 10.0,
    price: 95.50,
    filled: 0,
    status: 'canceled',
    fee: 0,
    feeAsset: 'USDT',
    commission: 0,
    commissionAsset: 'USDT',
    createTime: '2024-02-20 11:15:30',
    updateTime: '2024-02-20 11:45:10',
    fills: []
  },
  {
    id: 'ORD103',
    symbol: 'ADAUSDT',
    side: 'buy',
    type: 'market',
    quantity: 1000.0,
    filled: 1000.0,
    status: 'filled',
    executedPrice: 0.4705,
    fee: 0.47,
    feeAsset: 'USDT',
    pnl: 15.80,
    commission: 0.47,
    commissionAsset: 'USDT',
    createTime: '2024-02-20 10:20:45',
    updateTime: '2024-02-20 10:20:47',
    fills: [
      {
        id: 'FILL004',
        price: 0.4705,
        quantity: 1000.0,
        commission: 0.47,
        commissionAsset: 'USDT',
        time: '2024-02-20 10:20:47'
      }
    ]
  },
  {
    id: 'ORD104',
    symbol: 'BTCUSDT',
    side: 'sell',
    type: 'stop',
    quantity: 0.1,
    price: 43000.00,
    filled: 0.1,
    status: 'filled',
    executedPrice: 43000.00,
    fee: 4.30,
    feeAsset: 'USDT',
    pnl: -180.50,
    commission: 4.30,
    commissionAsset: 'USDT',
    createTime: '2024-02-19 16:30:20',
    updateTime: '2024-02-19 18:45:15',
    fills: [
      {
        id: 'FILL005',
        price: 43000.00,
        quantity: 0.1,
        commission: 4.30,
        commissionAsset: 'USDT',
        time: '2024-02-19 18:45:15'
      }
    ]
  },
  {
    id: 'ORD105',
    symbol: 'ETHUSDT',
    side: 'buy',
    type: 'limit',
    quantity: 3.0,
    price: 2600.00,
    filled: 2.5,
    status: 'filled',
    executedPrice: 2600.00,
    fee: 6.50,
    feeAsset: 'USDT',
    pnl: 107.50,
    commission: 6.50,
    commissionAsset: 'USDT',
    createTime: '2024-02-19 14:15:10',
    updateTime: '2024-02-19 15:20:30',
    fills: [
      {
        id: 'FILL006',
        price: 2600.00,
        quantity: 1.5,
        commission: 3.90,
        commissionAsset: 'USDT',
        time: '2024-02-19 15:10:25'
      },
      {
        id: 'FILL007',
        price: 2600.00,
        quantity: 1.0,
        commission: 2.60,
        commissionAsset: 'USDT',
        time: '2024-02-19 15:20:30'
      }
    ]
  },
  {
    id: 'ORD106',
    symbol: 'SOLUSDT',
    side: 'sell',
    type: 'market',
    quantity: 5.0,
    filled: 5.0,
    status: 'filled',
    executedPrice: 97.25,
    fee: 0.49,
    feeAsset: 'USDT',
    pnl: 62.25,
    commission: 0.49,
    commissionAsset: 'USDT',
    createTime: '2024-02-19 09:30:45',
    updateTime: '2024-02-19 09:30:47',
    fills: [
      {
        id: 'FILL008',
        price: 97.25,
        quantity: 5.0,
        commission: 0.49,
        commissionAsset: 'USDT',
        time: '2024-02-19 09:30:47'
      }
    ]
  },
  {
    id: 'ORD107',
    symbol: 'BTCUSDT',
    side: 'buy',
    type: 'limit',
    quantity: 0.05,
    price: 44500.00,
    filled: 0,
    status: 'rejected',
    fee: 0,
    feeAsset: 'USDT',
    commission: 0,
    commissionAsset: 'USDT',
    createTime: '2024-02-18 20:15:30',
    updateTime: '2024-02-18 20:15:31',
    fills: []
  }
]

// API 函数
export const fetchTradingPairs = (): Promise<TradingPair[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockTradingPairs)
    }, 300)
  })
}

export const fetchOrderBook = (symbol: string): Promise<OrderBook> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockOrderBook)
    }, 200)
  })
}

export const fetchRecentTrades = (symbol: string): Promise<Trade[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockRecentTrades)
    }, 200)
  })
}

export const fetchBalances = (): Promise<Balance[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockBalances)
    }, 300)
  })
}

export const fetchActiveOrders = (): Promise<Order[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockActiveOrders)
    }, 300)
  })
}

export const createOrder = (orderRequest: CreateOrderRequest): Promise<Order> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const newOrder: Order = {
        id: 'ORD' + Date.now(),
        symbol: orderRequest.symbol,
        side: orderRequest.side,
        type: orderRequest.type,
        quantity: orderRequest.quantity,
        price: orderRequest.price,
        filled: 0,
        status: 'pending',
        createTime: new Date().toLocaleString('zh-CN'),
        updateTime: new Date().toLocaleString('zh-CN')
      }
      resolve(newOrder)
    }, 500)
  })
}

export const cancelOrder = (orderId: string): Promise<boolean> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const orderIndex = mockActiveOrders.findIndex(order => order.id === orderId)
      if (orderIndex !== -1) {
        mockActiveOrders[orderIndex].status = 'canceled'
        resolve(true)
      } else {
        resolve(false)
      }
    }, 300)
  })
}

export const fetchOrderHistory = (params: OrderQueryParams = {}): Promise<{
  orders: OrderHistory[]
  total: number
  page: number
  pageSize: number
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      let filteredOrders = [...mockOrderHistory]
      
      // 过滤条件
      if (params.symbol && params.symbol !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.symbol === params.symbol)
      }
      
      if (params.status && params.status !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.status === params.status)
      }
      
      if (params.side && params.side !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.side === params.side)
      }
      
      if (params.type && params.type !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.type === params.type)
      }
      
      if (params.startTime) {
        filteredOrders = filteredOrders.filter(order => order.createTime >= params.startTime!)
      }
      
      if (params.endTime) {
        filteredOrders = filteredOrders.filter(order => order.createTime <= params.endTime!)
      }
      
      // 按时间倒序排列
      filteredOrders.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
      
      // 分页
      const page = params.page || 1
      const pageSize = params.pageSize || 20
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      const paginatedOrders = filteredOrders.slice(startIndex, endIndex)
      
      resolve({
        orders: paginatedOrders,
        total: filteredOrders.length,
        page,
        pageSize
      })
    }, 800)
  })
}

export const getOrderStatistics = (): Promise<{
  totalOrders: number
  filledOrders: number
  canceledOrders: number
  totalVolume: number
  totalFees: number
  totalPnl: number
  winRate: number
}> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const totalOrders = mockOrderHistory.length
      const filledOrders = mockOrderHistory.filter(order => order.status === 'filled').length
      const canceledOrders = mockOrderHistory.filter(order => order.status === 'canceled').length
      
      const filledOrdersData = mockOrderHistory.filter(order => order.status === 'filled')
      const totalVolume = filledOrdersData.reduce((sum, order) => 
        sum + (order.executedPrice || 0) * order.filled, 0)
      const totalFees = filledOrdersData.reduce((sum, order) => sum + order.fee, 0)
      const totalPnl = filledOrdersData.reduce((sum, order) => sum + (order.pnl || 0), 0)
      
      const profitableOrders = filledOrdersData.filter(order => (order.pnl || 0) > 0).length
      const winRate = filledOrders > 0 ? (profitableOrders / filledOrders) * 100 : 0
      
      resolve({
        totalOrders,
        filledOrders,
        canceledOrders,
        totalVolume,
        totalFees,
        totalPnl,
        winRate
      })
    }, 500)
  })
}